#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::weak_ptr;
using std::shared_ptr;

void test0(){
    shared_ptr<int> sp(new int(10));
    weak_ptr<int> wp;//无参的方式创建weak_ptr
    wp = sp;//赋值

    /* weak_ptr<int> wp2(sp);//利用shared_ptr创建weak_ptr */

    *sp;
    //*wp;//不支持直接解引用
    cout << "sp.use_count():" << sp.use_count() << endl;
    cout << "wp.use_count():" << wp.use_count() << endl;

    //weak_ptr提升为shared_ptr
    shared_ptr<int> sp2 = wp.lock();
    if(sp2){
        cout << "提升成功" << endl;
        cout << *sp2 << endl;
    }else{
        cout << "提升失败，托管的空间已经被销毁" << endl;
    }

    cout << endl;
    weak_ptr<int> wp2;
    shared_ptr<int> sp3 = wp2.lock();
    if(sp3){
        cout << "提升成功" << endl;
        cout << *sp3 << endl;
    }else{
        cout << "提升失败，托管的空间已经被销毁" << endl;
    }
}

void test1(){
    weak_ptr<int> wp;
    {//块作用域
        shared_ptr<int> sp(new int(10));
        wp = sp;

        shared_ptr<int> sp2 = wp.lock();
        if(sp2){
            cout << "提升成功" << endl;
            cout << *sp2 << endl;
        }else{
            cout << "提升失败，托管的空间已经被销毁" << endl;
        }

        cout << endl;
        bool flag = wp.expired();
        if(flag){
            cout << "托管的空间已经被销毁" << endl;
        }else{
            cout << "托管的空间还在" << endl;
        }
    }
    cout << endl;
    shared_ptr<int> sp2 = wp.lock();
    if(sp2){
        cout << "提升成功" << endl;
        cout << *sp2 << endl;
    }else{
        cout << "提升失败，托管的空间已经被销毁" << endl;
    }

    cout << endl;
    bool flag = wp.expired();
    if(flag){
        cout << "托管的空间已经被销毁" << endl;
    }else{
        cout << "托管的空间还在" << endl;
    }
}

int main(void){
    test1();
    return 0;
}
